﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SPCFMedicineInformer.Helpers;
using System.Text;
using SPCFMedicineInformer.Constants;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.web;
using umbraco.NodeFactory;
using Vega.USiteBuilder;
using SPCFMedicineInformer.DocumentTypes;
using umbraco;
namespace SPCFMedicineInformer.Masterpages
{
    public partial class Admin_MedicineGenericNameDetails : System.Web.UI.MasterPage
    {
        static int id = 0;
        static int orig_cat_id = 0;
        static string orig_gen_name = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            int tempInt;
            id = Request.QueryString["id"] != null ? int.TryParse(Request.QueryString["id"].ToString(), out tempInt) ? tempInt : 1 : 0;
            bool isNew = Request.QueryString["n"] != null ? Request.QueryString["n"].ToString() == "1" ? true : false : false;
            btnDelete.Visible = id > 0 ? true : false;
            if (!IsPostBack)
            {
                BindDropdown();
                if (id > 0)
                {
                    var node = new Node(id);
                    var doc = node.NodeTypeAlias == "MedicineGenericName" ? ContentHelper.GetByNodeId<MedicineGenericName>(id) : null;
                    if (doc != null)
                    {
                        orig_gen_name = !string.IsNullOrEmpty(doc.GenericNameMT) ? doc.GenericNameMT : doc.Name;
                        txtGenericName.Text = orig_gen_name;
                        orig_cat_id = doc.ParentId;
                        ddlCategory.SelectedValue = orig_cat_id.ToString();
                        taContent.Value = doc.Description;
                        txtDisplayName.Text = doc.DisplayName;
                        
                        var strIdList = string.Join(",", node.GetChildNodesByType("MedicineItem").Select(a=>a.Id.ToString()).ToList());
                        litMedicines.Text = FormHelper.ParseIdToNameWithLink(strIdList, "", "/admin/utilities/medicine-entry/");
                        ShowContent(true);
                        if (isNew)
                            FormHelper.ShowMessage(MessageType.Done, "Generic Name Succesfully Saved!", MsgLiteral);

                    }
                    else
                        ShowContent(false);
                }
                
            }
        }
        void ShowContent(bool b)
        {
            plcContent.Visible = b;
            plcError.Visible = !b;
        }
        void Update()
        {
            if (id > 0)
            {
                int catId = int.Parse(ddlCategory.SelectedValue);
                var d = new Document(id);
                if (d != null)
                {
                    TransferDetailsToUmbraco(d);
                    if (catId != orig_cat_id)
                        UmbracoNodeHelper.MoveNode(catId, d.Id);
                }
            }
        }
        int AddNew()
        {
            DocumentType UmbracoDocType = DocumentType.GetByAlias("MedicineGenericName");
            int catId = int.Parse(ddlCategory.SelectedValue);
            if (catId > 0)
            {
                Document d = Document.MakeNew(StringUtils.TruncateIfLonger(txtGenericName.Text, 250), UmbracoDocType, User.GetUser(0), catId);
                TransferDetailsToUmbraco(d);
                return d.Id;
            }
            return 0;
        }
        void TransferDetailsToUmbraco(Document d)
        {
            d.Text = StringUtils.TruncateIfLonger(txtGenericName.Text,250);
            d.getProperty(UmbracoPropertyName.GENERIC_NAME_MT).Value = txtGenericName.Text;
            d.getProperty(UmbracoPropertyName.CONDITION_DESCRIPTION).Value = taContent.Value;
            d.getProperty(UmbracoPropertyName.DISPLAY_NAME).Value = txtDisplayName.Text;
            d.Publish(User.GetUser(0));
            umbraco.library.UpdateDocumentCache(d.Id);
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (IsValidate())
            {
                if (id > 0)
                {
                    Update();
                    FormHelper.ShowMessage(MessageType.Done, "Medicine Generic Succesfully Saved!", MsgLiteral);
                }
                else
                {
                    id = AddNew();
                    Response.Redirect("/admin/utilities/medicine-generic-name/generic-name-entry.aspx?id=" + id + "&n=1");
                }
            }
        }
        bool IsValidate()
        {
            bool result = true;
            int catId = int.Parse(ddlCategory.SelectedValue);
            var sb = new StringBuilder();
            var msgFormat = "<p class=\"{0}\">{1}</p>";
            if (catId == 0)
            {
                result = false;
                sb.AppendLine(string.Format(msgFormat, "msg warning", "Category is required!"));
            }
            if (string.IsNullOrWhiteSpace(txtGenericName.Text))
            {
                result = false;
                sb.AppendLine(string.Format(msgFormat, "msg warning", "Generic Name is required!"));
            }
            else if(catId > 0 && txtGenericName.Text.ToLower() != orig_gen_name.ToLower() && orig_cat_id != catId )
            {
                if (ContentHelper.GetByNodeId<MedicineCategory>(catId).GetChildren<MedicineGenericName>().Where(a => a.Name.ToLower() == txtGenericName.Text.ToLower()).Count() > 0)
                {
                    result = false;
                    sb.AppendLine(string.Format(msgFormat, "msg error", "Generic Name exist!"));
                } 
            }
            if (!result)
            {
                MsgLiteral.Visible = true;
                MsgLiteral.Text = sb.ToString();
            }
            return result;
        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("/admin/utilities/medicine-generic-name");
        }
        void BindDropdown()
        {
            var categoryList = NodeLocator.GetNodesOfExactType<MedicineCategory>();
            ddlCategory.Items.Clear();
            ddlCategory.DataSource = categoryList;
            ddlCategory.DataTextField = "Name";
            ddlCategory.DataValueField = "Id";
            ddlCategory.DataBind();
            ddlCategory.Items.Insert(0, new ListItem("Choose...", "0"));
        }
        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            Response.Redirect("/admin/utilities/medicine-generic-name/generic-name-entry");
        }
        void Delete(int id)
        {
            if (id > 0)
            {
                Document doc = new Document(id);
                if (doc.Published)
                {
                    doc.UnPublish();
                    library.UnPublishSingleNode(doc.Id);
                }
                doc.delete();
                Response.Redirect("/admin/utilities/medicine-generic-name");
            }
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            Delete(id);
        }
        
    }
}